package com.app.aop;

import cn.hutool.json.JSONObject;
import com.app.pojo.Status;
import com.app.utils.CookieUtils;
import com.app.utils.TokenManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LoginCheckAop {
    @Pointcut("within(com.app.controller.*) && @annotation(com.app.aop.LoginCheck)")
    public void pointCut(){}

    @Autowired
    private TokenManager tokenManager;
    String NOT_LOGIN_RES = new JSONObject().set("status", Status.USER_NOT_SIGNED_IN).toString();
    String SYS_ERROR_RES = new JSONObject().set("status", Status.SYSTEM_ERROR).toString();
//    public LoginCheckAop(TokenManager tokenManager) {
//        this.tokenManager = tokenManager;
//    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp){
        Object[] args = pjp.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];
        try {
            String token= CookieUtils.getValue(request.getCookies(),"token");
            String userId=CookieUtils.getValue(request.getCookies(),"userId");
            args[1]=userId;
            if (tokenManager.isLogged(userId,token))
                return pjp.proceed(args);
            return NOT_LOGIN_RES;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return SYS_ERROR_RES;
    }
}
